package com.financing.wap.web.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.ILogsService;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.StringUtil;

/**
 * Servlet Filter implementation class AccessFilter
 */
@Component(value="sysLogFilter")
public class SysLogFilter implements Filter,ApplicationContextAware{
	
	private Logger log = Logger.getLogger(this.getClass());
	
	private String msgStatusURI = "/wap/api/message/msgStatus";
	
	@Autowired
	protected ILogsService logsServiceImpl;
    /**
     * Default constructor. 
     */
    public SysLogFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		
		String URI = httpRequest.getRequestURI();
		Session session = SessionUtil.getSession(true);
		UserDTO loginUser = session.getUser();
			Map<String,Object> params = new HashMap<String,Object>();
			params.putAll(request.getParameterMap());
			
			List<Object> paramsRems = new ArrayList<Object>();
			
			Iterator<String> it = params.keySet().iterator();
			while(it.hasNext()){
				String para = it.next();
				if(para.toLowerCase().indexOf("password")!=-1){
					//params.remove(para);
					paramsRems.add(para);
				}
			}
			for(Object prarRem:paramsRems){
				params.remove(prarRem);
			}
			params.put("referer", httpRequest.getHeader("Referer"));
			params.put("ip", IPUtil.getRemoteHost(httpRequest));
			Cookie[] cookies =  httpRequest.getCookies();
			if(cookies != null){
				for(Cookie cookie:cookies){
					params.put(cookie.getName(),cookie.getValue());
				}
			}
			
			if(!msgStatusURI.equals(URI)){
				try {
					if(loginUser!= null){
						logsServiceImpl.addLog(URI, StringUtil.filUtf8mb4(JSONObject.fromObject(params).toString()), loginUser.getLoginName());
					}else{
						logsServiceImpl.addLog(URI, StringUtil.filUtf8mb4(JSONObject.fromObject(params).toString()), "system");
					}
				} catch (SQLException e) {
					log.warn("Write log error !",e);
				}
			}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		logsServiceImpl = (ILogsService) applicationContext.getBean("logsServiceImpl");
		
	}
	

}
